package com.rimi.servlet;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

import com.alibaba.excel.EasyExcel;
import com.rimi.bean.JsonResult;
import com.rimi.bean.Page;
import com.rimi.bean.User;
import com.rimi.service.RoleService;
import com.rimi.service.UserService;
import com.rimi.service.impl.RoleServiceImpl;
import com.rimi.service.impl.UserServiceImpl;
import com.rimi.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/user")
public class UserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();
    private RoleService roleService = new RoleServiceImpl();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取要执行的动作
        String method = request.getParameter("method");
        if("add".equals(method)){
            //添加
            add(request,response);
        }else if ("pupdate".equals(method)){
            //预修改
            pupdate(request,response);
        } else if ("update".equals(method)){
            //修改
            update(request,response);
        }else if("updateEnable".equals(method)){
            //启用或禁用
            updateEnable(request,response);
        }else if ("delete".equals(method)){
            //删除
            delete(request,response);
        }else if("outExcel".equals(method)){
            //导出excel
            outExcel(request,response);
        }else if("list".equals(method)){
            //跳转到列表页面
            request.setAttribute("roleList",roleService.findRoleList());
            request.getRequestDispatcher("/page/user/list.jsp").forward(request,response);
        }else if("addform".equals(method)){
            //跳转到列表页面
            request.setAttribute("roleList",roleService.findRoleList());
            request.getRequestDispatcher("/page/user/userform.jsp").forward(request,response);
        }else {
            //获取列表数据
            list(request,response);
        }
    }

    private void outExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //接收参数 1,2,3,4
        String ids = request.getParameter("ids");
        //通过ID查询对应的数据
        List<User> userList=userService.getUserListByIds(ids);
        //设置下载名称
        response.setContentType("application/vnd.ms-excel");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), User.class).sheet("第一页").doWrite(userList);
    }

    private void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String userId = request.getParameter("userId");
        String loginname = request.getParameter("loginname");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String userAvatar = request.getParameter("userAvatar");
        String role = request.getParameter("role");
        String enabled = request.getParameter("enabled");

        System.out.println("接收的用户名:"+username);
        //封装对象
        User user = new User();
        user.setUserId(Integer.parseInt(userId));
        user.setUserName(username);
        user.setUserPassword(password);
        user.setUserLoginName(loginname);
        user.setUserCreateTime(new Date());
        user.setUserAvatar(userAvatar);
        user.setRoleId(Integer.parseInt(role));
        if(!StringUtils.isEmpty(enabled) && "on".equals(enabled)){
            user.setUserEnable(0);
        }
        //
        boolean isok = userService.updateUser(user);
        //
        //
        PrintWriter writer = response.getWriter();
        writer.append(isok?JsonResult.SUCCESS().toJson():JsonResult.ERROR().toJson());
        writer.close();
    }

    private void pupdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        //通过Id查询用户原有的信息
        User user = userService.getUserById(id);
        request.setAttribute("user",user);
        request.setAttribute("roleList",roleService.findRoleList());
        request.getRequestDispatcher("/page/user/update.jsp").forward(request,response);
    }

    private void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //接收表单数据
        String loginname = request.getParameter("loginname");
        String username = request.getParameter("username");
        String userAvatar = request.getParameter("userAvatar");
        String role = request.getParameter("role");
        String enabled = request.getParameter("enabled");
        //将表单数据封装成一个User对象
        User user = new User();
        user.setUserName(username);
        user.setUserLoginName(loginname);
        user.setUserPassword("123456");
        user.setUserCreateTime(new Date());
        user.setUserAvatar(userAvatar);
        user.setRoleId(0);
        //如果用户开启了
        if("on".equals(enabled)){
            user.setUserEnable(0);
        }
        //调用业务层方法
        boolean isok=userService.saveUser(user);
        //
        PrintWriter writer = response.getWriter();
        writer.append(isok?JsonResult.SUCCESS().toJson():JsonResult.ERROR().toJson());
        writer.close();
    }

    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //接收参数
        String ids = request.getParameter("ids");
        //调用业务层
        boolean isok = userService.dropUserBy(ids);
        //做出响应
        PrintWriter writer = response.getWriter();
        writer.append(isok?JsonResult.SUCCESS().toJson():JsonResult.ERROR().toJson());
        writer.close();;
    }

    private void updateEnable(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //接收参数
        String userId = request.getParameter("userId");
        String userEnable = request.getParameter("enable");
        //调用业务层完成修改操作
        boolean isok=userService.updateEnable(userId,userEnable);
        PrintWriter writer = response.getWriter();
        writer.append(isok?JsonResult.SUCCESS().toJson():JsonResult.ERROR().toJson());
        writer.close();
    }


    /**
     * 查询用户列表动作
     * @param request
     * @param response
     */
    private void list(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        //获取分页条件
        String page = request.getParameter("page");
        String limit = request.getParameter("limit");
        //封装分页条件对象
        Page p = new Page();
        if(!StringUtils.isEmpty(page)){
            p.setNowPage(Integer.parseInt(page));
        }
        p.setPageSize(Integer.parseInt(limit));
        //获取查询条件
        String loginname = request.getParameter("loginname");
        String username = request.getParameter("username");
        String roleId = request.getParameter("role");
        //封装查询条件
        User user = new User();
        user.setUserLoginName(loginname);
        user.setUserName(username);
        if(!StringUtils.isEmpty(roleId)){
            user.setRoleId(Integer.parseInt(roleId));
        }
        //根据条件获取用户列表数据
        List<User> userList = userService.getUserListBy(user, p);
        //根据查询条件 统计数据 总条数
        int count = userService.countUserBy(user);
        //拼接json格式的数据响应
        writer.append(JsonResult.SUCCESS(userList).append("count",count).toJson());
        //释放资源
        writer.close();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       doPost(request, response);
    }
}
